import re

#密文偏移
CAR_ENCODE_BASE_CHAR='.'
#允许的字符集
CAR_INFO_LEGAL_REGX_STRING=r"[^\.\da-zA-Z0-9\:\"\,\{\}]+"
CAR_INFO_LEGAL_REGX = re.compile(CAR_INFO_LEGAL_REGX_STRING)

def replaceChar(index,string,char):
	t = list(string)
	t[index] = char
	return ''.join(t)

def encodeString(jsonString):
	jsonString = CAR_INFO_LEGAL_REGX.sub("", jsonString)
	if len(jsonString)<21:
		return ""

	infoEncodeString = jsonString
	code = ""
	# 单独加密密文
	for i in range(9,19):
		currentCh=infoEncodeString[i]
		if currentCh<'0' or currentCh>'9':
			return ""
		code = code + currentCh
		ch = chr(ord(currentCh) - ord('0') + ord(CAR_ENCODE_BASE_CHAR))
		# infoEncodeString[i] = ch
		infoEncodeString = replaceChar(i,infoEncodeString,ch)

	codeIndexArray=[1,2,3,4,5,6,7,8,9,0]
	infoEncodeStringLen=len(infoEncodeString)
	index=0
	for i in range(0,infoEncodeStringLen):
		if i>=9 and i<=18 :
			continue
		ch = chr(ord(infoEncodeString[i])+ord(code[index])-ord('0'))
		index = codeIndexArray[index]
		# infoEncodeString[i] = ch
		infoEncodeString = replaceChar(i,infoEncodeString,ch)

	return infoEncodeString

def decodeString(encodeString):
	if len(encodeString)<21:
		return ""

	infoEncodeString = encodeString
	code = ""
	# 单独解密密文
	for i in range(9,19):
		currentCh=infoEncodeString[i]
		ch = chr(ord(currentCh) + ord('0') - ord(CAR_ENCODE_BASE_CHAR))
		code = code + ch
		# infoEncodeString[i] = ch
		infoEncodeString = replaceChar(i,infoEncodeString,ch)

	codeIndexArray=[1,2,3,4,5,6,7,8,9,0]
	infoEncodeStringLen=len(infoEncodeString)
	index=0
	for i in range(0,infoEncodeStringLen):
		if i>=9 and i<=18 :
			continue
		ch = chr(ord(infoEncodeString[i])-ord(code[index])+ord('0'))
		index = codeIndexArray[index]
		# infoEncodeString[i] = ch
		infoEncodeString = replaceChar(i,infoEncodeString,ch)

	return infoEncodeString







#=====================================================================================#
def main():
	jsonStr = "{\"code\":\"1232223289\",\"no\":\"12345\",\"lon\":0.0,\"lat\":0.0,\"v\":0.0,\"b\":0}"
	jsonStr = "{\"code\":\"1232223289\"}"
	encodeStr=encodeString(jsonStr)
	deCodeStr=decodeString(encodeStr)
	print(encodeStr)
	print(deCodeStr)

main()